package org.knife.springbootlearn.security.domain.service.impl;

import org.knife.springbootlearn.security.app.service.UserRoleService;
import org.knife.springbootlearn.security.domain.entity.TUser;
import org.knife.springbootlearn.security.domain.entity.TUserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 通过实现{@link UserDetailsService}来实现自定义认证
 * @author tianhao.luo@hand-china.com
 * @version 1.0
 * @date 2021年12月02日 星期四 9:17 上午
 * @description
 * @since 1.0
 */
@Service
public class MyCustomerUserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        TUser tUser = userRoleService.selectByUserName(s);
        List<TUserRole> tUserRoles = userRoleService.listByUserName(s);
        return changeToUser(tUser,tUserRoles);
    }


    private UserDetails changeToUser(TUser tUser,List<TUserRole> roleList){
        // 权限列表
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        // 赋予查询到的角色
        for (TUserRole tUserRole : roleList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(tUserRole.getRoleName());
            authorities.add(authority);
        }
        // 创建UserDetails对象，设置用户名、密码和权限
        return new User(tUser.getUserName(), tUser.getPwd(), authorities);
    }
}
